// pages/store/card/index/index.js
import Dialog from '@vant/weapp/dialog/dialog';
import Notify from '@vant/weapp/notify/notify';
import Toast from '@vant/weapp/toast/toast';
import { cardApplyStat } from '../../../common/enums';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    CustomBar: getApp().globalData.CustomBar,
    scrollHeight: '100vh',
    countList: [],
    isQryNextPage: true,
    qryParam: {
      status: 1,
      current: 1,
      size: 10,
    },
    cardApplyList: [],
    currStat: 1,
    show: false,
    actiTitleColumns: [],
    actiMap: [],
  },
  getScrollHeight() {
    // 获取内容区域的高度
    wx.createSelectorQuery().selectViewport().scrollOffset((res) => {
      this.setData({ scrollHeight: res.scrollHeight + 'px' });
    }).exec()
  },
  onScrollToLower() {
    if (this.data.isQryNextPage) {
      this.qryCardApplyList(true);
    }
  },
  onScroll(event) {
    let isScrollEnd = false;
    if (event.detail.scrollTop > 10) {
      isScrollEnd = true;
    }
    if (isScrollEnd != this.data.isScrollEnd) {
      this.setData({ isScrollEnd: isScrollEnd })
    }
    this.setData({ scrollTop: event.detail.scrollTop });
  },
  queryCardCount() {
    Toast.loading({
      message: '加载中...',
      forbidClick: true,
    });
    getApp().callContainer('/api/store/card/queryCount', {}, (res) => {
      this.setData({ countList: res.data.data.countList || [] });
      Toast.clear();
    }, () => {
      Toast.clear();
    })
  },
  // 过滤标签更新
  onChangeCurrStat(event) {
    const currStat = event.currentTarget.dataset.operation;
    this.setData({ currStat: currStat, 'qryParam.status': currStat, isQryNextPage: true });
    this.qryCardApplyList();
  },
  // 查询卡片审核列表
  qryCardApplyList(isNextPage) {
    Toast.loading({
      message: '加载中...',
      forbidClick: true,
    });
    // 是否需要走下一页查询
    let isQryNextPage = false;
    if (isNextPage && this.data.cardApplyList.length >= this.data.qryParam.current * this.data.qryParam.size) {
      isQryNextPage = true;
      this.setData({ 'qryParam.current': this.data.qryParam.current + 1 })
    } else if (!isNextPage) {
      this.setData({ 'qryParam.current': 1 })
    }
    getApp().callContainer('/api/user/card/listApply', this.data.qryParam, (res) => {
      if (res.data.data.records && res.data.data.records.length > 0) {
        for (const cardApply of res.data.data.records) {
          cardApply.status_label = cardApplyStat.get(cardApply.status);
          if (isQryNextPage) {
            // 如果查询结果小于查询条数，则下一次不继续分页查询
            if (res.data.data.records.length < this.data.qryParam.size) {
              this.setData({ isQryNextPage: false })
            }
            this.data.cardApplyList.push(cardApply);
          }
        }
      }
      if (isNextPage) {
        this.setData({ cardApplyList: this.data.cardApplyList });
      } else {
        this.setData({ cardApplyList: res.data.data.records || [] });
      }
      this.loadTmpFile();
      Toast.clear();
    }, () => {
      Toast.clear();
    })
  },
  // 缓存图片
  loadTmpFile() {
    for (const cardApply of this.data.cardApplyList) {
      if (!cardApply.imgUrl) {
        continue;
      }
      // 加载卡片图片
      getApp().getTempFilePath(cardApply.imgUrl).then((res) => {
        cardApply.tmpImgUrl = res;
        this.setData({ cardApplyList: this.data.cardApplyList });
      })
    }
  },
  // 卡片申请详情
  onClickCardApply(event) {
    const userCardApplyId = event.currentTarget.dataset.operation;
    wx.navigateTo({
      url: '/pages/store/card/apply/detail/detail?userCardApplyId=' + userCardApplyId,
    })
  },
  // 卡片详情
  onClickCardList(event) {
    const card = event.currentTarget.dataset.operation;
    wx.navigateTo({
      url: '/pages/store/card/list/list?cardId=' + card.cardId + "&cardName=" + card.cardName,
    })
  },
  queryActiList() {
    getApp().callContainer('/api/actiQuery/list', {}, (res) => {
      if (res.data.data.actiList != null) {
        const actiTitleColumns = [];
        const actiMap = new Map();
        for (const acti of res.data.data.actiList) {
          actiTitleColumns.push(acti.actiTitle);
          actiMap.set(acti.actiTitle, acti.actiId);
        }
        this.setData({ actiTitleColumns: actiTitleColumns, actiMap: actiMap });
      }
    })
  },
  onClickToExportUseRecord() {
    this.queryActiList();
    this.setData({ show: true })
  },
  onClose() {
    this.setData({ show: false })
  },
  onConfirm(event) {
    const actiId = this.data.actiMap.get(event.detail.value);
    this.setData({ show: false })
    Dialog.confirm({
      message: '确定导出吗？',
    }).then(() => {
      const param = {
        actiId: actiId
      }
      getApp().callContainer('/api/user/card/exportUseRecord', param, (res) => {
        Notify({ type: 'success', message: '导出成功！', top: this.data.CustomBar });
        // 打开文档
        if (res.data.data.fileId) {
          getApp().getTempFilePath(res.data.data.fileId).then((res) => {
            wx.openDocument({
              filePath: res,
              showMenu: true,
              success: function (res) {
                console.log('打开文档成功', res)
              }
            })
          })
        }
      })
    }).catch(() => { });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.queryCardCount();
    this.qryCardApplyList();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.queryCardCount();
    this.qryCardApplyList();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})